<template>
  <dialog-card
    :dilogAddTitle="options.type === 'add' ? '新建函数' : '编辑函数'"
    :isVisable="options.show"
    @closeDialog="handleFuntionClose"
    @save="handleFuntionSave(formRef)"
    :isFooter="true"
  >
    <el-form ref="formRef" :model="form" label-width="100">
      <el-form-item label="函数名称">
        <el-input v-model="form.name" clearable placeholder="请输入函数名称" />
      </el-form-item>
      <el-form-item label="函数备注">
        <el-input
          v-model="form.remark"
          clearable
          placeholder="请输入函数备注"
        />
      </el-form-item>
      <el-form-item label="数据处理函数">
        <monaco-editor
          v-model="form.value"
          width="100%"
          height="320px"
          language="javascript"
        />
      </el-form-item>
    </el-form>
  </dialog-card>
</template>

<script setup name="FuncList">
import { ref, reactive, watch, toRefs, defineAsyncComponent } from "vue"
import DialogCard from "@lowcode/components/dialog-card"

const monacoEditor = defineAsyncComponent(() =>
  import("@lowcode/components/MonacoEditor/index.vue")
)

const emit = defineEmits(["onSure", "onCancel"])

const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {
        show: false,
        type: "add", // 用于判断是编辑还是删除 add edit
        curFunction: null, // 当前编辑的变量
      }
    },
  },
})

const formRef = ref()
const data = reactive({
  form: {
    // 函数名称
    name: "",
    // 函数值
    value: "",
    // 备注
    remark: "",
  },
})

// 添加、修改设备
const handleFuntionSave = async formEl => {
  if (!formEl) return
  await formEl.validate(valid => {
    if (valid) {
      emit("onSure", {
        name: data.form.name,
        value: data.form.value,
        remark: data.form.remark,
        type: props.options.type,
        index: props.options.index,
      })
      handleFuntionClose()
    }
  })
}
// 关闭事件
const handleFuntionClose = () => {
  data.form = {
    name: "",
    value: "",
    remark: "",
  }
  formRef.value.resetFields()
  emit("onCancel")
}

watch(
  () => props.options,
  val => {
    if (val.type === "edit") {
      const curFunction = JSON.parse(JSON.stringify(val.curFunction))
      for (let key in data.form) {
        data.form[key] = curFunction[key]
      }
    }
  },
  { deep: true }
)

const { form, rules } = toRefs(data)
</script>

<style lang="scss" scoped></style>
